"""
Gua框架日志系统 - 基于Linus设计哲学的极简日志实现
单一数据结构，统一处理，零配置
"""
import time
import json
import logging
from typing import Any, Dict, Optional, List
import threading


class Event:
    """单一事件结构 - 这就是全部数据结构"""
    
    def __init__(self, level: str, message: str, **data: Any):
        self.timestamp = time.time()
        self.level = level  # DEBUG, INFO, WARN, ERROR
        self.message = message
        self.data = data  # 所有上下文数据都在这里
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "timestamp": self.timestamp,
            "level": self.level,
            "message": self.message,
            **self.data
        }
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"{self.level}: {self.message} {self.data}"


class GuaLogger:
    """统一日志记录器 - 基于标准库，零魔法"""
    
    def __init__(self, name: str, output: str = "console", file_path: Optional[str] = None):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)  # 设置最低级别，由handler控制
        self.output = output
        self._setup_handler(file_path)
    
    def _setup_handler(self, file_path: Optional[str]):
        """设置日志处理器"""
        # 清除现有处理器
        self.logger.handlers.clear()
        
        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        
        if self.output == "file" and file_path:
            # 文件输出
            handler = logging.FileHandler(file_path)
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
        elif self.output == "json":
            # JSON输出 - 使用简单的处理器
            handler = logging.StreamHandler()
            handler.setFormatter(logging.Formatter('%(message)s'))
            self.logger.addHandler(handler)
        else:
            # 控制台输出（默认）
            handler = logging.StreamHandler()
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
    
    def log(self, level: str, event_name: str = None, message: str = None, **data):
        """统一日志入口 - 消除参数冲突"""
        # 如果没有提供message，使用event_name作为message
        if message is None:
            message = event_name
        
        # 如果event_name在data中，提取出来
        if 'event_name' in data:
            event_name = data.pop('event_name')
        
        # 如果message在data中，提取出来
        if 'message' in data:
            message = data.pop('message')
        
        # 如果都没有，使用默认值
        if event_name is None:
            event_name = "unknown_event"
        if message is None:
            message = "no message"
        
        event = Event(level, message, event_name=event_name, **data)
        
        if self.output == "json":
            getattr(self.logger, level.lower())(json.dumps(event.to_dict()))
        else:
            getattr(self.logger, level.lower())(str(event))
    
    def debug(self, event_name=None, message=None, **data): self.log("DEBUG", event_name, message, **data)
    def info(self, event_name=None, message=None, **data): self.log("INFO", event_name, message, **data)
    def warn(self, event_name=None, message=None, **data): self.log("WARNING", event_name, message, **data)
    def error(self, event_name=None, message=None, **data): self.log("ERROR", event_name, message, **data)


class SimpleMonitor:
    """简单性能监控 - 不搞复杂的东西"""
    
    def __init__(self, logger: GuaLogger, max_samples: int = 1000):
        self.logger = logger
        self.request_times: List[float] = []
        self.error_count = 0
        self.total_requests = 0
        self.max_samples = max_samples
        self._lock = threading.Lock()  # 线程安全
    
    def record_request(self, duration: float, is_error: bool = False):
        """记录请求"""
        with self._lock:
            self.request_times.append(duration)
            self.total_requests += 1
            if is_error:
                self.error_count += 1
            
            # 保持固定大小，防止内存泄漏
            if len(self.request_times) > self.max_samples:
                self.request_times.pop(0)
    
    def get_stats(self) -> Dict:
        """获取统计信息：平均响应时间、最大响应时间、错误率"""
        with self._lock:
            if not self.request_times:
                return {
                    "avg_response_time": 0,
                    "max_response_time": 0,
                    "error_rate": 0,
                    "total_requests": 0
                }
            
            return {
                "avg_response_time": sum(self.request_times) / len(self.request_times),
                "max_response_time": max(self.request_times),
                "error_rate": self.error_count / self.total_requests if self.total_requests > 0 else 0,
                "total_requests": self.total_requests
            }


# 全局默认日志记录器
_default_logger = None


def get_default_logger() -> GuaLogger:
    """获取默认日志记录器"""
    global _default_logger
    if _default_logger is None:
        _default_logger = GuaLogger("gua")
    return _default_logger


def set_default_logger(logger: GuaLogger):
    """设置默认日志记录器"""
    global _default_logger
    _default_logger = logger